<?php


namespace App\Web\Controller;

use App\Web\Facades\UserAuth;
use App\Web\Model\CaseFlow;
use App\Web\Model\Member as MemberModel;
use EchoPHP\Http\Request;
use App\Web\Model\Report as ReportModel;

class Report extends Controller {

    /**
     * 校验权限
     * @param Request $request
     * @return array|bool
     */
    protected function chkTeamReportRight(Request $request) {
        $teamCode = $request->getParam('teamcode', '');
        $startDate = $request->getParam('startdate');
        $endDate = $request->getParam('enddate');


        $loginTeamCode = UserAuth::getLoginInfo('teamcode');
        $isSuperAdmin = UserAuth::ckhSuperLeader();

        if (!UserAuth::ckhTeamLeader() && !$isSuperAdmin) {
            return false;
        }
        //超管可以查看任意团队，非超管只能看当前团队
        if (!$isSuperAdmin && empty($teamCode)) {
            $teamCode = $loginTeamCode;
        } else if (!$isSuperAdmin && strpos($teamCode, $loginTeamCode) !== 0) {
            return false;
        }

        //查询时间
        $startDate = ($startDate ?? date('Y-m-d')) . ' 00:00:00';
        $endDate = ($endDate ?? date('Y-m-d')) . ' 23:59:59';

        return [
            'teamCode' => $teamCode,
            'startDate' => $startDate,
            'endDate' => $endDate
        ];
    }

    /**
     * 获取团队列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamReport(Request $request) {
        if (!($requestParams = $this->chkTeamReportRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $reportModel = new ReportModel();
        $result = $reportModel->teamReport($requestParams['teamCode'], $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取团队-项目报表数据
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamProjectReport(Request $request) {
        if (!($requestParams = $this->chkTeamReportRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $reportModel = new ReportModel();
        $result = $reportModel->teamProjectReport($requestParams['teamCode'], $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取团队-职位报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamCaseReport(Request $request) {
        if (!($requestParams = $this->chkTeamReportRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $projectId = $request->getParam('projectid', 0);

        $reportModel = new ReportModel();
        $result = $reportModel->teamCaseReport($requestParams['teamCode'], $projectId, $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取简历明细code列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function teamResumeList(Request $request) {
        if (!($requestParams = $this->chkTeamReportRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $projectId = $request->getParam('projectid', 0);
        $caseId = $request->getParam('caseid', 0);
        $flowCode = $request->getParam('flowcode', '');

        $reportModel = new ReportModel();
        $result = $reportModel->resumeListByTeam($requestParams['teamCode'], $projectId, $caseId, $flowCode, $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取简历内容
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getResumeInfoList(Request $request) {
        $keyCodes = $request->getParam('keycodes', '');
        $keyCodes = explode(',', $keyCodes);
        $keyCodes = array_filter($keyCodes);

        $loginUserId = UserAuth::getLoginId();

        $reportModel = new ReportModel();
        $result = $reportModel->resumeInfoList($loginUserId, $keyCodes);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 用户报表数据操作权限
     * @param Request $request
     * @return array|bool
     */
    protected function chkUserReportRight(Request $request) {
        $isSuper = UserAuth::ckhSuperLeader();
        $isLeader = UserAuth::ckhTeamLeader();

        $loginTeamCode = UserAuth::getLoginInfo('teamcode');

        $teamCode = $request->getParam('teamcode', '');
        $startDate = $request->getParam('startdate');
        $endDate = $request->getParam('enddate');

        if (!$isSuper && !$isLeader) {
            //普通成员，只能看自己的数据
            $searchTeam = false;
        } elseif ($isSuper) {
            //可以查询所有团队所有成员
            $searchTeam = true;
        } else {
            //查询团队用户成员列表
            $searchTeam = true;
            //默认查询当前团队
            if (empty($teamCode)) {
                $teamCode = $loginTeamCode;
            } elseif (strpos($teamCode, $loginTeamCode) !== 0) {
                //查询了与自身无关的团队
                return false;
            }
        }

        //查询时间
        $startDate = ($startDate ?? date('Y-m-d')) . ' 00:00:00';
        $endDate = ($endDate ?? date('Y-m-d')) . ' 23:59:59';

        return [
            'searchTeam' => $searchTeam,
            'teamCode' => $teamCode,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];
    }

    /**
     * 检查用户查看其它成员的权限
     * @param Request $request
     */
    protected function chkUserMemberRight(Request $request) {
        $isSuper = UserAuth::ckhSuperLeader();
        $isLeader = UserAuth::ckhTeamLeader();

        $loginUserId = UserAuth::getLoginInfo('userid');
        $loginTeamCode = UserAuth::getLoginInfo('teamcode');

        $userId = $request->getParam('userid', '');
        $startDate = $request->getParam('startdate');
        $endDate = $request->getParam('enddate');

        if (!$isSuper && !$isLeader && $loginUserId != $userId) {
            //普通成员，不是自己数据，不查询数据
            return false;
        } elseif ($isSuper) {
            //可以查询所有团队所有成员
        } elseif ($isLeader) {
            //查询是否是自己的下属成员
            $memberModel = new MemberModel();
            if (!$memberModel->chkIsMember($userId, $loginTeamCode)) {
                return false;
            }
        }

        //查询时间
        $startDate = ($startDate ?? date('Y-m-d')) . ' 00:00:00';
        $endDate = ($endDate ?? date('Y-m-d')) . ' 23:59:59';

        return [
            'userId' => $userId,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];
    }

    /**
     * 用户报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function userReport(Request $request) {
        if (!($requestParams = $this->chkUserReportRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $data = [
            'totalCount' => 0,
            'pagenum' => 1
        ];

        if ($requestParams['searchTeam']) {
            //查询用户列表
            $pageNum = $request->getParam('pagenum/d', 1);
            $pageLimit = $request->getParam('pagelimit/d');

            $search = [
                'userid' => $request->getParam('cname'),
                'username' => $request->getParam('username'),
                'teamcode' => $requestParams['teamCode'],
                'withchild' => $request->getParam('withchild', 0),
                'islock' => $request->getParam('islock'),     //在职状态改锁定状态
                'teammember' => 1,//查询团队成员
            ];

            $memberModel = new MemberModel();
            list($pageNum, $rowFrom, $rowTo) = $memberModel->paginationParameters($pageNum, $pageLimit);

            $count = $memberModel->getMemberListCount($search, $requestParams['teamCode']);
            $data['totalCount'] = intval($count);
            $data['pagenum'] = $pageNum;
            $memberList = $memberModel->getMemberList($search, $rowFrom, $rowTo, $requestParams['teamCode']);

            $data['userList'] = $memberList['memberList'];
        } else {
            $data['totalCount'] = 1;
            $data['pagenum'] = 1;
            $userInfo = [
                "userid" => UserAuth::getLoginInfo('userid'),
                "username" => UserAuth::getLoginInfo('username'),
                "cname" => UserAuth::getLoginInfo('cname'),
                "teamid" => UserAuth::getLoginInfo('teamid'),
                "teamrole" => UserAuth::getLoginInfo('teamrole'),
                "islock" => UserAuth::getLoginInfo('islock'),
                "teamcode" => UserAuth::getLoginInfo('teamcode'),
                "leader" => UserAuth::getLoginInfo('leader'),
                "teamname" => '',
            ];
            $data['userList'] = [$userInfo];
        }

        $userIds = [];
        foreach ($data['userList'] as $item) {
            $userIds[] = intval($item['userid']);
        }

        $reportModel = new ReportModel();
        $reportData = $reportModel->userReport($userIds, $requestParams['startDate'], $requestParams['endDate']);
        $data['reportData'] = $reportData['reportData'];

        return $this->json(['status' => true, 'message' => 'success', 'data' => $data]);
    }

    /**
     * 用户-项目报表
     */
    public function userProjectReport(Request $request) {
        if (!($requestParams = $this->chkUserMemberRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $reportModel = new ReportModel();
        $result = $reportModel->userProjectReport($requestParams['userId'], $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取团队-职位报表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function userCaseReport(Request $request) {
        if (!($requestParams = $this->chkUserMemberRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $projectId = $request->getParam('projectid', 0);

        $reportModel = new ReportModel();
        $result = $reportModel->userCaseReport($requestParams['userId'], $projectId, $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取简历明细code列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function userResumeList(Request $request) {
        if (!($requestParams = $this->chkUserMemberRight($request))) {
            return $this->json(['status' => true, 'message' => 'success', 'data' => []]);
        }

        $projectId = $request->getParam('projectid', 0);
        $caseId = $request->getParam('caseid', 0);
        $flowCode = $request->getParam('flowcode', '');

        $reportModel = new ReportModel();
        $result = $reportModel->resumeListByUser($requestParams['userId'], $projectId, $caseId, $flowCode, $requestParams['startDate'], $requestParams['endDate']);

        return $this->json([
            'status' => true,
            'message' => 'success',
            'data' => $result
        ]);
    }

    /**
     * 获取完整流程节点
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getDefaultList() {
        $caseFlowModel = new CaseFlow();
        $flowList = $caseFlowModel->getDefaultFlow(true);
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'flowlist' => $caseFlowModel->transFlowToNotAssoc($flowList)
        ]);
    }
}